const path = require("path");
const fs = require("fs/promises");
const { createReadStream } = require("fs");
const mime = require("mime");

module.exports = function static(dirname) {
  //插件接受参数，返回中间件，可以定制化这个中间件
  return async function (ctx, next) {
    let accessPath = path.join(dirname, ctx.path);
    try {
      let statObj = await fs.stat(accessPath);
      if (statObj.isFile()) {
        ctx.type =
          (mime.getType(accessPath) || "text/plain") + ";charset=utf-8";
        ctx.body = createReadStream(accessPath);
      } else {
        // 其他的情况，说明此中间件无法处理，交给后续逻辑来出来
        return next();
      }
    } catch (e) {
      return next();
    }
  };
};
